package recite.word.client.service.impl;

import cn.hutool.core.util.StrUtil;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import recite.word.client.dto.file.SendMessageDTO;
import recite.word.client.dto.file.TranslateDTO;
import recite.word.client.dto.verify.VerifyUtil;
import recite.word.client.service.IFileService;
import recite.word.redis.constant.RedisConstant;
import recite.word.redis.util.RedisUtil;
import recite.word.service.base.common.request.BaseRequest;
import recite.word.service.base.util.ali.MessageUtil;
import recite.word.service.base.util.ali.TranslateUtil;
import recite.word.service.base.util.common.Asserts;
import recite.word.service.base.util.file.FileUtil;
import recite.word.service.base.util.tengxun.TXFileUtil;

import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.regex.Pattern;

@Service
public class FileServiceImpl implements IFileService {
    @Autowired
    private TXFileUtil txFileUtil;
    @Autowired
    private TranslateUtil translateUtil;
    @Autowired
    private MessageUtil messageUtil;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 上传文件到腾讯云
     */
    @Override
    public String imgUpload(MultipartFile file){
        try {
            return txFileUtil.upload(file);
        } catch (IOException e){
            Asserts.isTrue(false,"上传文件失败");
        }
        return null;
    }

    /**
     * 图片识别 传一个图片和语言（eng/chi_sim）
     */
    @Override
    public String Tess4J(MultipartFile file, String language) {
        // 语言库位置（修改为跟自己上一步下载的语言库文件夹的路径）
        String languagePath = System.getProperty("user.dir")+"\\lang";
        System.out.println("路径: "+languagePath);
        ITesseract instance = new Tesseract();
        //设置训练库的位置
        instance.setDatapath(languagePath);
        //chi_sim简体中文， eng英文
        instance.setLanguage(language);
        String result = null;
        try {
            File pngFile = FileUtil.toPng(file);
            result =  instance.doOCR(pngFile);
            // 删除生成的png图片
            boolean delete = pngFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
            Asserts.isTrue(false,"没有识别到英文");
        }
        return result;
    }

    /**
     * 阿里云文字翻译 en->zh
     */
    @Override
    public String translate(BaseRequest<TranslateDTO> dto) {
        return translateUtil.translate(dto.getData().getEnglish());
    }

    /**
     * 阿里云发送短信
     */
    @Override
    public void sendMessage(BaseRequest<SendMessageDTO> dto) {
        SendMessageDTO data = dto.getData();
        Asserts.isTrue(data.getType() == 1 || data.getType() == 2, "类型参数有误");
        Asserts.isTrue(verifyPhone(data.getPhone()),"手机格式有误！");
        // 一分钟内不重复生成
        String key1 = RedisConstant.MES_REGIST_INTERVAL + data.getPhone();
        Asserts.isTrue(!redisUtil.hasKey(key1),"一分钟内不重复发送");
        // 生成验证码
        Random random = new Random();
        String code = String.valueOf(random.nextInt(9000) + 1000);
        try {
            messageUtil.send(data.getPhone(),code);
        } catch (Exception e) {
            Asserts.isTrue(false,"发送短信失败");
        }
        // 验证码存到redis
        String key2 = "";
        if (data.getType() == 1) { //注册
            key2 = RedisConstant.MES_REGIST_PREFIX + data.getPhone();
        } else { // 忘记密码
            key2 = RedisConstant.MES_RSTPWD_PREFIX + data.getPhone();
        }
        redisUtil.set(key2,code,RedisConstant.REDIS_DEFAULT_CODE_TIMEOUT);
        redisUtil.set(key1,code,RedisConstant.REDIS_MESSAGE_INTERVAL);
    }

    public static boolean verifyPhone(String phone) {
        String regex = "^[1]([3-9])[0-9]{9}$";
        boolean isMatch = false;
        if (StrUtil.isEmpty(phone)) {
            return false;
        } else if (phone.length() != 11) {
            return false;
        } else {
            isMatch = Pattern.matches(regex, phone);
        }
        return isMatch;
    }
}
